package carcassonne.server.websocket;

import carcassonne.lobby.Room;
import carcassonne.server.websocket.message.MessageIn;
import carcassonne.server.websocket.message.MessageOut;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;

// 一个websocket消息，这个消息都是以room为载体
public class WebsocketContext {

    public final Channel channel;

    public final Room room;

    public final MessageIn message;

    public final String raw;

    public WebsocketContext(Channel channel, Room room, MessageIn message, String raw) {
        this.channel = channel;
        this.room = room;
        this.message = message;
        this.raw = raw;
    }

    public int GetInt() {
        return Integer.parseInt(message.data);
    }

    public String GetString() {
        return message.data;
    }

    public <T> T GetObject(Class<T> clazz) {
        return JSON.parseObject(message.data, clazz);
    }

    public List<Integer> GetIntegerArray() {
        return JSON.parseArray(message.data, Integer.class);
    }

    public List<String> GetStringArray() {
        return JSON.parseArray(message.data, String.class);
    }

    public void Write(String path, Object data) {
        MessageOut mo = new MessageOut(message.seq, path, message.type, data);
        channel.writeAndFlush(new TextWebSocketFrame(mo.ToJsonString()));
    }

    public void Error(String message) {
        channel.writeAndFlush(new TextWebSocketFrame(MessageOut.Error(message).ToJsonString()));
    }

    public boolean IsHost() {
        return room.HostChannelID.equals(channel.id());
    }
}
